﻿using AOOR.Utilities;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Website.Interfaces;

namespace Website.Models
{
    public class SiteDefinitionManager : ISiteDefinitionManager
    {
        private const string filenameFormat = "SiteDefinition.{0}.xml";
        private SiteDefinition _siteDefinition;
        private ObjectSerializer _siteDefinitionSerializer;

        public SiteDefinitionManager(string path, ICultureManager cultureManager)
        {
            string culture = cultureManager.GetCultureName();
            _siteDefinitionSerializer = new ObjectSerializer(Path.Combine(path, string.Format(filenameFormat, culture)));
            _siteDefinition = _siteDefinitionSerializer.Deserialize<SiteDefinition>();
        }

        public SiteDefinition SiteDefinitions
        {
            get
            {
                return _siteDefinition;
            }
            set
            {
                _siteDefinition = value;
            }
        }

        public void AddLink(Models.WebLink link)
        {
            if (link.Id == 0)
            {
                link.Id = Enumerable.Max(_siteDefinition.Links, m => m.Id) + 1;
            }
            _siteDefinition.Links.Add(link);
        }

        public void RemoveLink(int id)
        {
            var link = (from l in _siteDefinition.Links
                        where l.Id == id
                        select l).First();
            _siteDefinition.Links.Remove(link);
        }

        public void DemoteLink(int id)
        {
            _siteDefinition.Links.DemoteEntry(p => p.Id == id);
        }

        public void PromoteLink(int id)
        {
            _siteDefinition.Links.PromoteEntry(p => p.Id == id);
        }

        private SiteDefinition ReadSiteDefinition(string location)
        {
            var serializer = new XmlSerializer(typeof(SiteDefinition));
            var streamReader = new StreamReader(location);

            var info = (SiteDefinition)serializer.Deserialize(streamReader);

            streamReader.Close();

            return info;
        }
    }
}
